//
//  ZYGifDecoder.m
//  ZYWebImage
//
//  Created by wangzhipan on 2025/3/6.
//

#import "ZYGifDecoder.h"
#import "UIImage+Extra.h"
#import "IZYImageCacheProtocol.h"

@interface ZYGifDecoder (){
    NSData *_data;
}

@end

@implementation ZYGifDecoder
- (instancetype)initWithData:(NSData *)data
{
    if (self = [super init]) {
        _data = data;
    }
    return self;
}

- (UIImage *)decodeImage
{
    NSData *data = _data;
    if (!data || data.length == 0) {
        return nil;
    }
    CGFloat scale = MAX(1, [UIScreen mainScreen].scale);
    
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (!source) {
        return nil;
    }
    
    size_t frameCount = CGImageSourceGetCount(source);
    if (frameCount == 0) {
        CFRelease(source);
        return nil;
    }
    
    // 如果只有一帧，按静态图片处理
    if (frameCount == 1) {
        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, 0, NULL);
        UIImage *image = [UIImage imageWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
        CGImageRelease(imageRef);
        CFRelease(source);
        return image;
    }
    
    NSMutableArray *frames = [NSMutableArray array];
    NSMutableArray *delays = [NSMutableArray array];
    
    // 处理每一帧
    for (size_t i = 0; i < frameCount; i++) {
        // 获取帧延时
        NSDictionary *frameProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
        NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
        NSNumber *delay = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        if (delay.doubleValue < 0.02) {
            delay = @0.1; // 修正过短的延时
        }
        [delays addObject:delay];
        
        // 解码帧
        CGImageRef frameImage = CGImageSourceCreateImageAtIndex(source, i, NULL);
        if (!frameImage) {
            continue;
        }
        
        size_t imageWidth = CGImageGetWidth(frameImage);
        size_t imageHeight = CGImageGetHeight(frameImage);
        size_t scaledWidth = imageWidth * scale;
        size_t scaledHeight = imageHeight * scale;
        
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(NULL,
                                                   scaledWidth,
                                                   scaledHeight,
                                                   8,
                                                   scaledWidth * 4,
                                                   colorSpace,
                                                   kCGImageAlphaPremultipliedFirst);
        
        if (!context) {
            CGImageRelease(frameImage);
            CGColorSpaceRelease(colorSpace);
            continue;
        }
        
        CGContextScaleCTM(context, scale, scale);
        CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), frameImage);
        
        CGImageRef scaledImage = CGBitmapContextCreateImage(context);
        UIImage *frameUIImage = [UIImage imageWithCGImage:scaledImage scale:scale orientation:UIImageOrientationUp];
        [frames addObject:frameUIImage];
        
        // 清理资源
        CGImageRelease(scaledImage);
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
        CGImageRelease(frameImage);
    }
    
    CFRelease(source);
    
    // 创建动画图片
    if (frames.count > 0) {
        NSTimeInterval totalDuration = 0;
        for (NSNumber *delay in delays) {
            totalDuration += delay.doubleValue;
        }
        UIImage *image = [UIImage animatedImageWithImages:frames duration:totalDuration];
        image.zy_format = ZYImageFormatGif;
        return image;
    }
    
    return nil;
}
@end
